package controller

import (
	"ims/app/wechat/apidao/gf_wxfans"
	"ims/app/wechat/apptype"
	"ims/app/wechat/wapi"
	"ims/library/response"
	"time"

	"github.com/gogf/gf/encoding/gurl"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/util/gconv"
	"github.com/skip2/go-qrcode"
)

var Index = indexController{}

type indexController struct{}

//这个是对接公众号的 服务器url 的验证
func (c *indexController) Index(r *ghttp.Request) {
	var req *apptype.GetSignature
	r.Parse(&req)
	echostr := req.Echostr
	// 直接返回就可以了
	r.Response.Write(echostr)
}

//获取公众号的access_token
func (c *indexController) Welcome(r *ghttp.Request) {

	var req apptype.Wechat = apptype.AppidAndSecret

	access_token, _ := wapi.GetAccessToken(req)
	var token *apptype.AccessToken

	if access_token != nil {
		if err := gconv.Struct(access_token, &token); err != nil {
			panic(err)
		}

	}
	openid := gconv.String(r.Get("openid"))
	if openid == "" {
		response.JsonExit(r, 1, "openid 必须")
	}
	//通过openid + 基础 access_token 获取微信用户基本资料
	url := "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" +
		token.Access_token + "&openid=" + openid + "&lang=zh_CN"

	if client, err := g.Client().Get(url); err != nil {
		response.JsonExit(r, 1, err.Error())
	} else {
		defer client.Close()
		var user gf_wxfans.Entity
		//wxfans表入库
		gconv.Struct(client.ReadAllString(), &user)
		if user.Openid == "" {
			response.JsonExit(r, 1, "获取微信用户资料失败")
		}
		//增加一个fans数据
		if id, err := wapi.WxfansService.AddFans(r.Context(), user); err != nil {
			response.JsonExit(r, 1, err.Error())
		} else {
			r.Response.Write(gconv.String(id))
		}

	}

	r.Response.Write(token.Access_token)
}

//这是调用go-grcode 模块输出一个二维码的 案例
func (c *indexController) Showqrcode(r *ghttp.Request) {

	f, err := qrcode.Encode("http://ngrok.siyueweb.cn/wechat/login", qrcode.Highest, 300)
	if err != nil {
		g.Log(err.Error())
	}
	r.Response.Write(f)
}

func (c *indexController) Login(r *ghttp.Request) {
	//判断cookie是否存在
	if r.Cookie.Get("wxuser_openid") != "" {
		r.Response.RedirectTo("/wechat/welcome?openid=" + r.Cookie.Get("wxuser_openid"))
	}

	//通过 网页授权接口获取 code并进行 获取openid
	var app apptype.Wechat = apptype.AppidAndSecret
	var redirect_uri string = gurl.Encode("http://ngrok.siyueweb.cn/wechat/login")

	var authorize_url string = "https://open.weixin.qq.com/connect/oauth2/authorize?" +
		"appid=" + app.Appid + "&redirect_uri=" + redirect_uri +
		"&response_type=code&scope=snsapi_base&state=fromgo#wechat_redirect"

	code := r.Get("code")
	if code == nil {
		r.Response.RedirectTo(authorize_url)
	}
	//r.Response.Write(code)

	var oauth_url string = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + app.Appid + "&secret=" + app.AppSecret + "&code=" + gconv.String(code) + "&grant_type=authorization_code"
	//定义变量，用来存放接口返回的值
	var ret *apptype.WebAccessToken

	client, _ := g.Client().Get(oauth_url)

	defer client.Close()

	if err := gconv.Struct(client.ReadAllString(), &ret); err != nil {
		panic(err)
	}
	//g.Dump(ret)
	//r.Response.Write(ret.Access_token)
	//流程的第三步完成，或得了网页授权登陆access_token
	var userinfo *apptype.UserInfo
	if ret.Errcode != 0 {
		panic(ret)
	}
	userinfo_url := "https://api.weixin.qq.com/sns/userinfo?access_token=" +
		ret.Access_token + "&openid=" + ret.Openid + "&lang=zh_CN"

	client, _ = g.Client().Get(userinfo_url)
	defer client.Close()
	gconv.Struct(client.ReadAllString(), &userinfo)
	//输出获取到的微信用户信息
	if userinfo.Errcode == 0 {
		r.Cookie.SetCookie("wxuser_openid", userinfo.Openid, "", "/", time.Minute*60*24*30)
	}
	//r.Response.Write(userinfo.Nickname + userinfo.Openid)
	//授权登陆成功跳转到welcome页面
	r.Response.RedirectTo("/wechat/welcome?openid=" + userinfo.Openid)

}
